package com.atguigu.hotitems_analysis;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Properties;

/**
 * @author Malegod_xiaofei
 * @create 2021-12-09-22:20
 */
public class KafkaProducerUtil {
    public static void main(String[] args) throws Exception {
        writeToKafka("hotitems");
    }

    // 包装一个写入 Kafka 的方法
    public static void writeToKafka(String topic) throws Exception {

        // Kafka 配置
        Properties properties = new Properties();
        properties.setProperty("bootstap.servers", "localhost:9092");
        properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringDeserializer");

        // 定义一个 Kafka Producer
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);

        // 用缓冲方式读取文本数据
        BufferedReader bufferedReader = new BufferedReader(new FileReader("F:\\x-gongzuo\\gitx\\UserBehaviorAnalysis\\HotItemsAnalysis\\src\\main\\resources\\UserBehavior.csv"));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            ProducerRecord<String, String> producerRecord = new ProducerRecord<>(topic, line);
            // 用 producer 发送数据
            kafkaProducer.send(producerRecord);
        }
        kafkaProducer.close();
    }
}
